var addrNum=0;//地址信息标识
var addrId=getUrlVal("addrId");//获取用户修改地址后的地址Id
var productId=getUrlVal("productId");//获取商品Id
var type=getUrlVal("type");//type==1积分购买，type==2金钱购买
var goodsTypes="";
var productIds="";
var endAddrId="";
var userMess="";
$(function(){
    //获取用户信息
    getUser();
    userMess=JSON.stringify(ym.user);
     getAddr();
});
/*查询地址信息*/
function getAddr(){
    if(addrId==undefined||addrId==null||addrId==""){
        addrId=0;
    }
    ym.ajax({
        url:'/shop/address/default',
        param:{
            receivingId:addrId,
            ymUser:userMess,
        },
        success:function(data){
            console.log(data)
            console.log("获取地址信息");
            if(data.obj==null||data.obj==undefined){
                $(".addAddr").removeClass("hide");
                addrNum=0;
            }else{
                $(".hasAddr").removeClass("hide");
                addrNum=1;
                endAddrId=data.obj.receivingId;
                $("#receiverName").html(data.obj.receiverName);
                $("#tel").html(data.obj.receiverPhone);
                var detailedAddress=(data.obj.detailedAddress).replace(/,/g, "");
                $(".contantAddr").html(detailedAddress+" "+data.obj.receiverAddress);
            }
        }
    });
    //查询商品信息
    getGoods();
};
//查询商品信息
function getGoods(){
    if(productId!=null&&productId!="null"&&productId!=""&&productId!=undefined){
       var goodsId=productId;
       var goodsType=type;
    }else{
        var goodsId=sessionStorage.getItem("productId");
        var goodsType=sessionStorage.getItem("type");
    }
    goodsTypes=goodsType;
    productIds=goodsId;
    ym.ajax({
        url:'/shop/product/getByPK',
        param:{
            productId:goodsId,
        },
        success:function(data){
            console.log(data)
            console.log("获取详情")
            var html="";
             if(data.obj!=null){
                  var l=data.obj;
                  html+='<li class="am-g am-g-collapse productId" productId="'+l.productId+'" types="'+goodsTypes+'">'
                  html+='<span class="goodsImgDiv">'
                  html+='<img src="'+l.productPic+'" class="goodsImg" />'
                  html+='</span>'
                  html+='<span class="goodsMessDivs">'
                  html+='<span class="goodName" style="height:40px;">'
                  html+='<span class="goodsName">'+l.productName+'</span>'
                  html+='</span>'
                  html+='<span class="goodsNumDiv" style="height:40px;">'
                  if(goodsType==1){//1积分购买，2金钱购买
                      html+='<span class="goodMoneyDiv ar-left" style="margin-top:3px;"><span>'+l.productPoint+'</span>积分</span>'
                  }else if(goodsType==2){
                      var productPrice=(l.productPrice)*0.01;
                      productPrice=productPrice.toFixed(2);
                      html+='<span class="goodMoneyDiv ar-left" style="margin-top:3px;">￥ <span intearges="'+l.productPoint+'">'+productPrice+'</span></span>'
                  }
                  html+='<span class="numDiv">'
                  html+='<span class="reduceNum bagReduce">-</span>'
                  html+='<input type="number" class="numInput" value="1" min="1"  />'
                  html+='<span class="addNum">+</span>'
                  html+='</span></span></span></li>'
                 $(".goodsDiv").append(html);
                  sumMoney(goodsType);
                 /*减数量*/
                 $(".reduceNum").click(function(){
                     var num=$(".numInput").val();
                     if(num==2){
                         $(this).addClass("bagReduce")
                     }
                     if(num==1){
                         return false;
                     }else{
                         num--;
                         $(".numInput").val(num);
                     }
                     sumMoney(goodsType);
                 })
                 /*加数量*/
                 $(".addNum").click(function(){
                     $(".reduceNum").removeClass("bagReduce");
                     var num=$(".numInput").val();
                     num++;
                     $(".numInput").val(num);
                     sumMoney(goodsType);
                 })
                 //数量输入的失去焦点事件
                 $(".numInput").blur(function(){
                     var num=$(this).val();
                     if(num<1){
                         $(this).val("1");
                     }
                     if(!/^\d+$/.test(num)){
                         $(this).val("1");
                     }
                     sumMoney(goodsType);
                 })
             }
        }
    });
}
/*计算总价*/
function sumMoney(goodsType){
    var allMoney=0;
    var unitPrice=$(".goodMoneyDiv span").html();
    var num=$(".numInput").val();
    num=parseInt(num);
    if(goodsType==1){//1积分购买，2金钱购买
        unitPrice=parseInt(unitPrice);
        allMoney=num*unitPrice;
        $(".moneys").html("<span class='totalFee'>"+allMoney+"积分</span>");
    }else if(goodsType==2){
        unitPrice=parseFloat(unitPrice);
        allMoney=num*unitPrice;
        allMoney=allMoney.toFixed(2);
        //获取积分
        var intearge=$(".goodMoneyDiv span").attr("intearges");
        var allIntearge=parseInt(intearge)*num;
        $(".moneys").html("￥ <span class='totalFee'>"+allMoney+"</span>+<span class='inteargeSpan'>"+allIntearge+"</span>积分");
    }

}
/*选择地址*/
function choiceAddr(){
    var productIds=$(".productId").attr("productId");
    sessionStorage.setItem("productId",productIds);
    var types=$(".productId").attr("types");
    sessionStorage.setItem("type",types);
    window.location.href="address.html?pageTips=1";
    //pageTips标识从哪个页面跳转到选择地址页面，1从商品订单过去，2从购物车订单过去
}
function setTime(){
    setTimeout(function () {
        $("#alertModal").modal('close');
    }, 2000);
}
/*提交订单*/
function buyGoods(){
    var num=0;
    if(addrNum==0){
        $("#alertModal .am-modal-bd").html("请先选择配送地址！")
        $("#alertModal").modal();
        setTimeout(function () {
            $("#alertModal").modal('close');
        }, 2000);
    }else{
        if(goodsTypes==1){//积分购买
            var totalFee=$(".totalFee").html();
            var price=$(".goodMoneyDiv span").html()
            totalFee=parseInt(totalFee)
            var shopOrderPayMethod=0;
            $('#myConfirm .am-modal-bd').html("您是否确认花费"+totalFee+"积分购买此商品？");
            var $confirm = $('#myConfirm');
            var confirm = $confirm.data('amui.modal');
            var onConfirm = function() {
                num++;
                if(num==1){
                    //点击确认按钮调用事件
                    ym.ajax({
                        url:'/shop/order/add',
                        param:{
                            totalFee:totalFee,
                            productId:productIds,
                            productNum:$(".numInput").val(),
                            price:price,
                            receivingId:endAddrId,
                            shopOrderPayMethod:shopOrderPayMethod,
                            ymUser:userMess,
                        },
                        success:function(data){
                            if(data.res==1){
                                $("#alertModal .am-modal-bd").html("购买成功！");
                                $("#alertModal").modal();
                                setTime();
                            }else{
                                $("#alertModal .am-modal-bd").html(data.resMsg);
                                $("#alertModal").modal();
                                setTimeout(function () {
                                    $("#alertModal").modal('close');
                                }, 2000);
                            }
                        }
                    });
                }
            };
            var onCancel = function() {
                //取消按钮调用事件
            };
            if (confirm) {
                confirm.options.onConfirm =  onConfirm;
                confirm.options.onCancel =  onCancel;
                confirm.toggle(this);
            } else {//重定义模态窗函数
                $confirm.modal({
                    relatedElement: this,
                    closeViaDimmer: false,//禁止点击遮罩层关闭
                    onConfirm: onConfirm,
                    onCancel: onCancel
                });
            }
        }else if(goodsTypes==2){//金钱购买
            var totalFee=$(".totalFee").html();
            var allIntearge=$(".inteargeSpan").html();
            var price=$(".goodMoneyDiv span").html();
            var prices=$(".totalFee").html();
            totalFee=parseInt(totalFee*100);
            price=parseInt(price*100);
            var shopOrderPayMethod=1;
            $('#myConfirm .am-modal-bd').html("您是否确认花费"+prices+"元+"+allIntearge+"积分购买此商品？");
            var $confirm = $('#myConfirm');
            var confirm = $confirm.data('amui.modal');
            var onConfirm = function() {
                num++;
                $(".masks").removeClass("hide");
                if(num==1){
                    //点击确认按钮调用事件
                   ym.ajax({
                        url:'/shop/order/add',
                        param:{
                            totalFee:totalFee,
                            productId:productIds,
                            productNum:$(".numInput").val(),
                            price:price,
                            receivingId:endAddrId,
                            shopOrderPayMethod:shopOrderPayMethod,
                            point:allIntearge,
                            ymUser:userMess,
                        },
                        success:function(data){
                            if(data.res==1){
                               //调支付接口
                                var orderId=data.obj;
                                payType(orderId,totalFee);
                            }else{
                                $("#alertModal .am-modal-bd").html(data.resMsg);
                                $("#alertModal").modal();
                                setTimeout(function () {
                                    $("#alertModal").modal('close');
                                    $(".masks").addClass("hide");
                                }, 2000);

                            }
                        }
                    });
                }
            };
            var onCancel = function() {
                //取消按钮调用事件
            };
            if (confirm) {
                confirm.options.onConfirm =  onConfirm;
                confirm.options.onCancel =  onCancel;
                confirm.toggle(this);
            } else {//重定义模态窗函数
                $confirm.modal({
                    relatedElement: this,
                    closeViaDimmer: false,//禁止点击遮罩层关闭
                    onConfirm: onConfirm,
                    onCancel: onCancel
                });
            }
        }
    }
}
/*两秒后关闭弹窗*/
function setTime(){
    setTimeout(function () {
        $("#alertModal").modal('close');
        window.location.href="order.html";
    }, 2000);
}


